<template>
  <!-- JSON 配置项 -->
  <div class="flex flex-row mx-[20px] justify-evenly mb-3">
    <el-switch active-color="rgb(126 34 206)" v-model="state.showLineNumber" inline-prompt active-text="显示行号"
      inactive-text="不显示行号" />
    <el-switch active-color="rgb(126 34 206)" v-model="state.showLine" inline-prompt active-text="显示线路"
      inactive-text="不显示线路" />
    <el-switch active-color="rgb(126 34 206)" v-model="state.showIcon" inline-prompt active-text="显示图标"
      inactive-text="不显示图标" />
    <el-switch active-color="rgb(126 34 206)" v-model="state.showLength" inline-prompt active-text="折叠显示长度"
      inactive-text="折叠不显示长度" />
    <el-switch active-color="rgb(126 34 206)" v-model="state.showDoubleQuotes" inline-prompt active-text="key引号"
      inactive-text="无key引号" />
  </div>
  <!-- JSON -->
  <section class="h-[600px] overflow-auto text-gray scrollbar" :style="jsonViewStyle">
    <vue-json-pretty :data="jsonData" :deep="deep" :showLength="state.showLength" :showLine="state.showLine"
      :showLineNumber="state.showLineNumber" :showIcon="state.showIcon" :showDoubleQuotes="state.showDoubleQuotes"
      @nodeClick="jsonClick"></vue-json-pretty>
  </section>
</template>

<script lang="ts" setup>
import VueJsonPretty from "vue-json-pretty";
import "vue-json-pretty/lib/styles.css";
import useClipboard from 'vue-clipboard3';

const { toClipboard } = useClipboard();

type JsonConfig = {
  showLength: boolean;
  showLine: boolean;
  showLineNumber: boolean;
  showIcon: boolean;
  showDoubleQuotes: boolean;
};

type StateObj = {
  deep?: number;
  [propName: string]: any;
} & JsonConfig;

type PropType = {
  data: any;
  deep?: number;
  jsonViewStyle?: any;
}

const props = withDefaults(defineProps<PropType>(), {
  data: {},
  deep: 3,
  jsonViewStyle: {},
})

const state = reactive<StateObj>({
  showLength: false,
  showLine: false,
  showLineNumber: false,
  showIcon: false,
  showDoubleQuotes: false,
});

const { jsonViewStyle, deep } = toRefs(props);
const jsonData = computed(() => props.data);

const jsonClick = async (data: any) => {
  if (!data.key) return
  let temp = data.content
  if (["{", "["].includes(temp)) {
    temp = '';
  }
  const str = `${data.key}${temp ? ':' + temp : ''}`;
  await toClipboard(str);
};
</script>
